from django.shortcuts import render, redirect

from tools.models import models
from tools.utils.Pagination import Pagination


def depart_list(request):
    """ 部门列表 """
    # # 去数据库获取所有的部门列表
    # # [对象，对象，对象]
    # querySet = models.Department.objects.all()
    #
    # return render(request, "depart_list.html", {"querySet": querySet})

    # 去数据库中获取所有的部门名称
    queryset = models.Department.objects.all()
    page_object = Pagination(request, queryset, page_size=10)  # 每页显示几条（page_size=2）
    context = {
        "querySet": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    print('depart_list的querySet',queryset)
    # return render(request, "../templates/testdepart/depart_list.html", {'querySet':queryset})
    return render(request, "../templates/testdepart/depart_list.html", context)


def depart_add(request):
    """ 添加部门 """
    if request.method == "GET":
        return render(request, "../templates/testdepart/depart_add.html")

    # 获取用户POST请求提交过来的数据（title输入为空，先不考虑，后续有组件判断）
    title = request.POST.get("title")

    # 保存到数据库
    models.Department.objects.create(title=title)

    # 重定向回列表页面
    return redirect("/tools/depart/list/")


def depart_delete(request):
    """ 删除部门 """
    # 获取ID http://localhost:8000/depart/delete/?nid=1
    nid = request.GET.get("nid")
    # 删除
    models.Department.objects.filter(id=nid).delete()

    # 重定向回列表页面
    return redirect("/tools/depart/list/")


# http://localhost:8000/depart/10/edit/
# http://localhost:8000/depart/2/edit/
# http://localhost:8000/depart/4/edit/
def depart_edit(request, nid):
    """ 修改部门 """
    if request.method == "GET":
        # 根据nid获取部门数据
        row_object = models.Department.objects.filter(id=nid).first()
        # print(row_object.id, row_object.title)

        return render(request, "../templates/testdepart/depart_edit.html", {"row_object": row_object})

    # 获取用户提交的标题
    title = request.POST.get("title")

    # 根据ID找到数据库中的数据并进行更新
    models.Department.objects.filter(id=nid).update(title=title)

    # 重定向回部门列表
    return redirect("/tools/depart/list/")

